/*
 * Atomic Predicates for Transformers
 * 
 * Copyright (c) 2015 UNIVERSITY OF TEXAS AUSTIN. All rights reserved. Developed
 * by: HONGKUN YANG and SIMON S. LAM http://www.cs.utexas.edu/users/lam/NRL/
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * with the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimers.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimers in the documentation
 * and/or other materials provided with the distribution.
 * 
 * 3. Neither the name of the UNIVERSITY OF TEXAS AUSTIN nor the names of the
 * developers may be used to endorse or promote products derived from this
 * Software without specific prior written permission.
 * 
 * 4. Any report or paper describing results derived from using any part of this
 * Software must cite the following publication of the developers: Hongkun Yang
 * and Simon S. Lam, Scalable Verification of Networks With Packet Transformers
 * Using Atomic Predicates, IEEE/ACM Transactions on Networking, October 2017,
 * Volume 25, No. 5, pages 2900-2915 (first published as IEEE Early Access
 * Article, July 2017, Digital Object Identifier: 10.1109/TNET.2017.2720172).
 * 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
 * THE SOFTWARE.
 */
package transformer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

import common.APComputer;
import common.PositionTuple;

public class NetworkIPinIPAP {

    NetworkAP net;
    ArrayList<String[]> tunnels;

    public NetworkIPinIPAP(String tunnel_file_name) throws IOException
    {
        net = new NetworkAP("i2");
        tunnels = read_tunnel_file(tunnel_file_name);

    }

    static public ArrayList<String[]> read_tunnel_file(String tunnel_file_name)
    {
        ArrayList<String[]> tunnels = new ArrayList<String[]>();

        try{
            FileInputStream fis = new FileInputStream(new File(tunnel_file_name));
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));

            String line = null;
            while ((line = br.readLine()) != null) {

                String[] path_info = line.split(" ");
                int path_len = path_info.length;
                String entry = path_info[0];
                String exit = path_info[path_len-2];
                String destination = path_info[path_len-1];

                String[] one_tunnel = new String[3];
                one_tunnel[0] = entry;
                one_tunnel[1] = exit;
                one_tunnel[2] = destination;

                tunnels.add(one_tunnel);

                System.out.println(entry+","+exit+","+destination);

            }

            br.close();
        } catch(Exception e)
        {
            e.printStackTrace();
        }

        return tunnels;
    }

    public void add_tunnels(int tunnel_num)
    {
        net.ini_IPinIP();

        int used_num = tunnel_num;
        if(used_num > tunnels.size())
        {
            used_num = tunnels.size();
        }

        for(int i = 0; i < used_num; i ++)
        {
            String[] tunnel = tunnels.get(i);
            net.add_ipinip_tunnel(tunnel[0], tunnel[1], tunnel[2]);
        }

        System.out.println(used_num + " tunnels added.");

        net.ap_first_iter();
        net.ap_ipinip();
    }
    
    private void add_one_tunnel_update(int tunnel_ind)
    {
        String[] tunnel = tunnels.get(tunnel_ind);
        net.add_ipinip_tunnel_update(tunnel[0], tunnel[1], tunnel[2]);
    }
    
    public void update()
    {
        int tunnel_num = tunnels.size();
        
        add_tunnels(tunnel_num-1);
        
        add_one_tunnel_update(tunnel_num-1);
        
        double ap_update = net.ap_ipinip_update();
        
        double tree_compute = compute_trees();
        
        System.out.println("AP Update Time:" + ap_update);
        System.out.println("Recompute Tree:" + tree_compute);
    }
    
    public double compute_trees()
    {
        HashSet<PositionTuple> pts = net.getallactiveports();
        System.out.println(pts.size() + " trees");
        return StateTransferAP.compute_trees_anypkt(net, pts, null);
    }
    
    public void update_port_predicate_ipinip()
    {
        ArrayList<int[]> updates = new ArrayList<int[]> ();
        add_tunnels(20);

        HashSet<Integer> predicates = new HashSet<Integer>();
        for(Box b : net.boxes.values())
        {
            int count = 0;
            // for each router, pick two port predicates
            int[] update = new int[2];

            if(b instanceof Device)
            {
                int size = ((Device) b).fwbdds.size();
                int[] picks = net.randPicksRange(1, size);
                
                for(int port_predicate : ((Device) b).fwbdds.values())
                {
                    count ++;
                    if(count == picks[0])
                    {
                        update[0] = port_predicate;
                    }else{
                        if(count == picks[1])
                        {
                            update[1] = port_predicate;
                            updates.add(update);
                        }
                        predicates.add(port_predicate);
                    }
                }
            }
        }
        
        APComputer apc = new APComputer(net.bddengine);
        net.apc = apc;
        
        ArrayList<IPinIP> tunnels = new ArrayList<IPinIP> ();
        for(Box b : net.boxes.values())
        {
            Device d = (Device) b;
            if(d.ip_in_ip != null)
            {
                tunnels.add(d.ip_in_ip);
            }
        }

        int size = apc.addPredicates(new ArrayList<Integer>(predicates));
        apc.computeExpressions();
        net.compute_ap_ipinip(tunnels);
       
                
        long update_time = 0;
        
        for(int[] update : updates)
        {
            long t1 = System.currentTimeMillis();

            apc.update_r(update[1]);
            apc.update_a(update[0]);

            net.compute_ap_ipinip(tunnels);;
            long t2 = System.currentTimeMillis();

            update_time += t2-t1;
            
            System.out.println(t2-t1);
        }
        
        System.out.println("update time: " + (1.0*update_time/updates.size())+ " ms");

    }

    public static void main(String [] args) throws IOException
    {
        NetworkIPinIPAP net_ipinip = new NetworkIPinIPAP("i2_ipinip_tunnels");
        //net_ipinip.add_tunnels(3);
        //net_ipinip.update();
        net_ipinip.update_port_predicate_ipinip();
    }

}
